﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Common.Interfaces;
using Kiiro.Model;
using Kiiro.SiteDefinition.Core;
using Kiiro.SiteDefinition.MasterPage;
using Microsoft.SharePoint.Utilities;

namespace Kiiro.SiteDefinition.ControlTemplates
{
    public partial class ProjectSummary : System.Web.UI.UserControl
    {
        public BasePage Base
        {
            get { return ( BasePage ) Page; }
        }

        private Project project;
        public Project Project
        {
            get { return project; }
            set { project = value; }
        }

        protected override void OnPreRender ( EventArgs e )
        {
            base.OnPreRender ( e );

            litProjectContentId.Text = Project.Id.ToString ( );
            hidProjectId.Value = Project.Id.ToString ( );

            //Passing project server relative web url to get the right group name
            PermissionsModel.GetGlobalPermissionBitsForCurrentUser ( Project, Base.CurrentUser, Base.SiteCollectionId, Project.ServerRelativeWebUrl );

            lnkProjectTitle.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( Project.Title );
            lnkProjectTitle.NavigateUrl = Project.ServerRelativeWebUrl;
            lnkProjectTitle.Visible = SPHelpers.IsPortal ( Base.SiteCollectionId, Base.ServerRelativeUrl );
            lblProjectTitle.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( Project.Title );
            lblProjectTitle.Visible = !SPHelpers.IsPortal ( Base.SiteCollectionId, Base.ServerRelativeUrl );

            double today = Math.Round((Project.ActualWork / Project.TotalWork) * 100, 0);
            today = today > 100 ? 100 : today;
            today = !Double.IsNaN ( today ) && !Double.IsInfinity ( today ) ? today : 0;
            lblTodayPercentage.Text = string.Format ( "{0}%", today.ToString ( ) );

            double shouldBe = Math.Round((Project.ProjectedWork / Project.TotalWork) * 100, 0);
            shouldBe = shouldBe > 100 ? 100 : shouldBe;
            shouldBe = !Double.IsNaN ( shouldBe ) && !Double.IsInfinity ( shouldBe ) ? shouldBe : 0;
            lblShouldBePercentage.Text = String.Format ( "{0}%", shouldBe.ToString ( ) );

            // good/bad/ugly image
            if ( ( shouldBe - today ) < 10 )
            {
                imgProgressIcon.ImageUrl = "/_layouts/images/Kiiro/good.png";
                imgProgressIcon.AlternateText = "good";
            }
            else if ( ( shouldBe - today ) < 30 && ( shouldBe - today ) >= 10 )
            {
                imgProgressIcon.ImageUrl = "/_layouts/images/Kiiro/bad.png";
                imgProgressIcon.AlternateText = "bad";
            }
            else
            {
                imgProgressIcon.ImageUrl = "/_layouts/images/Kiiro/ugly.png";
                imgProgressIcon.AlternateText = "ugly";
            }

            // bar chart (percentage complete)
            int progressGutterWidth = 234;
            progressBar.Style.Add ( "width", progressGutterWidth * ( today / 100 ) + "px" );

            lblSummaryNote.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( Project.SummaryNote );
            txtSummaryNote.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( Project.SummaryNote );
            if ( ( project.PermissionBitsProjects [ 1 ] && project.PermissionBitsProjects [ 2 ] ) )
            {
                divSummaryNoteUpdate.Visible = true;
                divSummaryNote.Visible = false;
            }
            else
            {
                divSummaryNoteUpdate.Visible = false;
                divSummaryNote.Visible = true;
                divSummaryNote.Visible = !string.IsNullOrEmpty ( lblSummaryNote.Text );
            }

            string stats = "{0} {1}, {2} {3}";

            lnkTasks.NavigateUrl = Project.ServerRelativeWebUrl + Constants.ProjectFileUrls.WorkAll;
            string numTLate = Project.TaskStats.Count > 0 ? Project.TaskStats [ 0 ] : "0";
            string numSlipping = Project.TaskStats.Count > 1 ? Project.TaskStats [ 1 ] : "0";
            lblTasks.Text = String.Format ( stats, numTLate, "Late", numSlipping, "Slipping" );

            lnkIssues.NavigateUrl = Project.ServerRelativeWebUrl + Constants.ProjectFileUrls.WorkAll;
            string numILate = Project.IssueStats.Count > 0 ? Project.IssueStats [ 0 ] : "0";
            string numHighPriority = Project.IssueStats.Count > 1 ? Project.IssueStats [ 1 ] : "0";
            lblIssues.Text = String.Format ( stats, numILate, "Late", numHighPriority, "High Priority" );

            lnkDocuments.NavigateUrl = Project.ServerRelativeWebUrl + Constants.ProjectFileUrls.Documents;
            string numDocNew = Project.DocumentStats.Count > 0 ? Project.DocumentStats [ 0 ] : "0";
            string numDocUpdated = Project.DocumentStats.Count > 1 ? Project.DocumentStats [ 1 ] : "0";
            lblDocuments.Text = String.Format ( stats, numDocNew, "New", numDocUpdated, "Updated This Week" );

            lnkDiscussions.NavigateUrl = Project.ServerRelativeWebUrl + Constants.ProjectFileUrls.DiscussionsAll;
            string numDiscNew = Project.DiscussionStats.Count > 0 ? Project.DiscussionStats [ 0 ] : "0";
            string numDiscUpdated = Project.DiscussionStats.Count > 1 ? Project.DiscussionStats [ 1 ] : "0";
            lblDiscussions.Text = String.Format ( stats, numDiscNew, "New", numDiscUpdated, "Updated This Week" );


            List<TeamMember> teamMembers = TeamModel.GetTeamMembers ( Base.SiteCollectionId, Project.ServerRelativeWebUrl );
            teamMembers.Sort ( new Comparison<TeamMember> ( SortTeamMembersTopDown ) );
            //setting the text to empty to ensure that duplicate information not produced when there is a post back on the page
            litCarousel.Text = string.Empty;
            foreach ( TeamMember teamMember in teamMembers )
            {
                string memberRole = string.Empty;
                if (!string.IsNullOrEmpty(teamMember.RoleOnProject))
                {
                    if (teamMember.RoleOnProject.Length > 30)
                    {
                        memberRole = teamMember.RoleOnProject.Substring(0, 27) + "...";
                    }
                    else
                    {
                        memberRole = teamMember.RoleOnProject;
                    }
                }
                litCarousel.Text += string.Format ( @"<li>
                        <dl class='userNameTitle'>
                          <dt><img src='{0}' class='userImgSmall' /></dt>
                          <dd><span href='{1}' class='userNameLink'>{2}</span></dd>
                          <dd><span>{3}</span></dd>
                        </dl>
                        <dl class='userContact'>
                          <dd><span class='highlight'>Phone: </span><span>{4}</span></dd>
                          <dd><span class='highlight'>Email: </span><span href='mailto:{5}' class='userNameLink'>{5}</span></dd>
                          <dd><span class='highlight'>IM: </span><span>{6}</span></dd>
                        </dl>
                    </li>",
                    teamMember.User.PictureUrl ?? "/_layouts/images/Kiiro/person-thumb.gif",
                    string.Format ( "{0}{1}?id={2}", Base.ServerRelativeUrl, Constants.PortalFileUrls.UserDisplay, teamMember.User.SPUserId ),
                    SPHelpers.ConvertHtmlToKiiroSafeText ( teamMember.User.FullName ),
                    SPHelpers.ConvertHtmlToKiiroSafeText ( memberRole ),
                    SPHelpers.ConvertHtmlToKiiroSafeText ( teamMember.User.PhoneNumber ),
                    SPHelpers.ConvertHtmlToKiiroSafeText ( teamMember.User.Email ),
                    SPHelpers.ConvertHtmlToKiiroSafeText ( teamMember.User.IM ) );
            }

            bool isProject = SPHelpers.IsProject ( Base.SiteCollectionId, Base.ServerRelativeUrl );

            //change "false" to "isProject" to show who updated status note last
            lastUpdatedStatusEdit.Visible = false;// isProject;
            lastUpdatedStatusDisplay.Visible = false;// isProject;

            if (isProject)
            {
                string lastUpdated = string.Format("Project status note updated: {0} By {1}.",
                    FormattingHelpers.DateTimeToDisplayDateStringNoLine(Project.ModifiedDate),
                    Project.LastUpdatedSummaryNote);

                lastUpdatedStatusEdit.InnerText = lastUpdated;
                lastUpdatedStatusDisplay.InnerText = lastUpdated;

                //assign the current user name to the hidden field
                hidCurrentUser.Value = string.IsNullOrEmpty(Base.CurrentUser.FullName) ? "Unknown" : Base.CurrentUser.FullName;
            }
        }

        private int SortTeamMembersTopDown ( TeamMember x, TeamMember y )
        {
            int returnValue = default ( int );

            if ( x == null && y == null )
            {
                returnValue = 0;
            }
            else if ( x != null && y == null )
            {
                returnValue = -1;
            }
            else if ( x == null && y != null )
            {
                returnValue = 1;
            }
            else
            {
                returnValue = y.IsProjectManager.CompareTo ( x.IsProjectManager );

                if ( returnValue == 0 )
                {
                    if ( x.User == null && y.User == null )
                    {
                        returnValue = 0;
                    }
                    else if ( x.User != null && y.User == null )
                    {
                        returnValue = -1;
                    }
                    else if ( x.User == null && y.User != null )
                    {
                        returnValue = 1;
                    }
                    else
                    {
                        if ( string.IsNullOrEmpty ( x.User.LastName ) && string.IsNullOrEmpty ( y.User.LastName ) )
                        {
                            returnValue = 0;
                        }
                        else if ( !string.IsNullOrEmpty ( x.User.LastName ) && string.IsNullOrEmpty ( y.User.LastName ) )
                        {
                            returnValue = -1;
                        }
                        else if ( string.IsNullOrEmpty ( x.User.LastName ) && !string.IsNullOrEmpty ( y.User.LastName ) )
                        {
                            returnValue = 1;
                        }
                        else
                        {
                            returnValue = x.User.LastName.CompareTo ( y.User.LastName );
                        }
                    }
                }
            }

            return returnValue;
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/CONTROLTEMPLATES/Kiiro/ProjectSummary.ascx.cs $
 * 
 * 26    1/12/10 2:33p Camerons
 * 
 * 25    12/17/09 11:11a Shafia
 * 
 * 24    12/15/09 11:05a Shafia
 * added check to set today % and should be % to 100 if it is over 100.
 * 
 * 23    10/26/09 9:27a Adamw
 * 
 * 22    10/23/09 5:51p Adamw
 * Case 348
 * 
 * 21    19/10/09 1:14p Shafia
 * 
 * 20    8/10/09 3:27p Camerons
 * 
 * 19    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 18    30/09/09 9:38a Shafia
 * 
 * 17    14/09/09 9:21a Shafia
 * 
 * 16    2/09/09 10:06a Shafia
 * 
 * 15    31/08/09 12:19p Shafia
 * added hidden field to hold current user full name to pass it if status
 * note is updated using ajax
 * 
 * 14    19/08/09 1:20p Camerons
 * Removed the extra blank space (hide last updated labels) when control
 * is being displayed on the Dashboard
 * 
 * 13    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/